package se.webbzon.oschi01.region;

import java.awt.geom.Point2D;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;

import se.webbzon.oschi01.singleton.Singletons;
import se.webbzon.oschi01.world.Chunk;
import se.webbzon.oschi01.world.DefaultRegion;
import se.webbzon.oschi01.world.Region;

public class URLRegion implements Region {
	
	private URL url;
	
	private Region r;
	
	public URLRegion(URL url) {
		this(url,new DefaultRegion());
	}

	public URLRegion(URL url, Region region) {
		this.url = url;
		this.r = region;
	}
	
	@Override public boolean addChunk(Chunk chunk) {
		return r.addChunk(chunk);
	}

	@Override public boolean removeChunk(Chunk chunk) {
		return r.removeChunk(chunk);
	}

	@Override public boolean hasChunk(Chunk chunk) {
		return r.hasChunk(chunk);
	}

	@Override public int chunks() {
		return r.chunks();
	}

	@Override public Chunk getChunk(int i) {
		return r.getChunk(i);
	}

	@Override public Chunk getChunk(Point2D coordinates) {
		return r.getChunk(coordinates);
	}

	@Override public Point2D getCoordinate() {
		return r.getCoordinate();
	}

	@Override public void setCoordinate(int x, int z) {
		r.setCoordinate(x, z);
	}

	@Override public boolean writeback() throws IOException {
		RegionWriter writer = Singletons.instance(RegionWriter.class);
		File file;
		try {
			file = new File(url.toURI());
		} catch (URISyntaxException e) {
			throw new IOException(e);
		}
		FileOutputStream fos = new FileOutputStream(file);
		writer.write(r, fos);
		fos.close();
		r.free();
		RegionReader reader = Singletons.instance(RegionReader.class);
		RegionReference ref = new RegionReference(url);
		r = reader.read(ref).r;
		return true;
	}

	@Override public void free() {
		r.free();
	}
	
	@Override public String toString() {
		return r.toString();
	}
	

}
